package nina.yiyou.salary.start

import nina.yiyou.performance.s20confirm.input.BasicExcelReaderV2
import nina.yiyou.performance.s20confirm.input.EmployeeServingFilterer
import nina.yiyou.salary.input.InfoExcelCollector
import nina.yiyou.salary.input.config.ConfigExcelReader
import nina.yiyou.salary.input.info.*
import nina.yiyou.salary.output.ResultMapMaker
import nina.yiyou.salary.output.SalaryResultGenerator
import nina.yiyou.salary.process.global.GlobalResultMaker
import nina.yiyou.salary.process.salary.SalaryProcessMapMaker

import java.nio.file.Files
import java.nio.file.Path

class WorkshopSalaryRunner {

  WorkshopSalaryRunner(SalaryArgsParser.Result args) {
    _args = args
  }

  void run() {
    Path workshopPath = _args.workshopExcel()
    assert Files.isRegularFile(workshopPath)

    Map globalMap = ConfigExcelReader.create(workshopPath).read().global()
    def (Map basicMap) = new InfoExcelCollector([
        ['in.花名册', { String p -> new BasicExcelReaderV2(p).read() }],
    ], globalMap, workshopPath).collect()

    def globalResult = new GlobalResultMaker(globalMap, workshopPath).make()
    List<Map> employResult = makeEmployeeResult(basicMap, globalMap, globalResult)

    println('导出csv...')
    new SalaryResultGenerator(workshopPath, employResult, globalResult.toMap()).generate()
  }

  private List<Map> makeEmployeeResult(Map basicMap, Map globalMap, GlobalResultMaker.Result globalResult) {
    def (payMap, etcMap, attendMap, insuranceMap, fundMap, bonusMap) = new InfoExcelCollector([
        ['in.薪资表', { String p -> new PayExcelReader(p).read() }],
        ['in.工资其他', { String p -> new EtcExcelReader(p).read() }],
//        ['in.考勤表', { String p -> new AttendExcelReader(p).read() }],
        ['in.考勤表2', { String p -> new AttendExcelV2Reader(p).read() }],
        ['in.社保表', { String p -> new InsuranceExcelV2Reader(p, basicMap, globalResult).read() }],
        ['in.公积金表', { String p -> new FundExcelV2Reader(p, basicMap).read() }],
        ['in.奖金表', { String p -> new BonusExcelReader(p).read() }],
    ], globalMap, globalResult.workshopPath()).collect()

    println('计算额外结果...')
    def computeMap = new SalaryProcessMapMaker(globalMap, globalResult,
        basicMap, etcMap, payMap, attendMap, insuranceMap, fundMap).make()

    return new ResultMapMaker([
        ['基本', new EmployeeServingFilterer(basicMap, attendMap).filter()],
        ['薪资', payMap],
        ['其他', etcMap],
        ['考勤', attendMap],
        ['社保', insuranceMap],
        ['奖金', bonusMap],
        ['计算', computeMap],
    ]).make().values().asList()
  }

  private final SalaryArgsParser.Result _args
}
